import os
import subprocess
import sys
import time
from config import *
import playaudio
def startRecordProcess():
    if os.path.exists("/opt"):
        record_process = subprocess.Popen(
            [f"{AUDIO_ROOT}/USBAudio/main", "plughw:0"],#opt/opi_test
            stderr=subprocess.PIPE
        )
    else:
        print("mimic recording audio")
def singleRecord():
    print("2s后开始录音，输入over结束")
    process = startRecordProcess()
    if process is not None:
        cnt=0
        while cnt<5:
            time.sleep(1)
            print(cnt,end="\r")
            cnt+=1
        process.terminate()
    else:
        print("record process is None")
    # 等待用户输入 "over" 来停止录音
    # for line in sys.stdin:
    #     time.sleep(5)
    #     record_process.terminate()
        # break
        # if "over" in line.strip().lower():
        #     # 停止录音
        #     record_process.terminate()
        #     print("录音结束。")
        #     break
def continualRecord():
    cnt=0
    while True:
        process = startRecordProcess()
        time.sleep(10)
        process.terminate()
        cnt+=1
        if os.path.exists(f"{AUDIO_ROOT}/USBAudio/audio.pcm"):
            os.rename(f"{AUDIO_ROOT}/USBAudio/audio.pcm",f"{AUDIO_ROOT}/USBAudio/audio_tmp{cnt%2}.pcm")
            yield f"{AUDIO_ROOT}/USBAudio/audio_tmp{cnt%2}.pcm"
        else:
            print("no audio file found named audio.pcm")
def convertAudio(forSTT=False):
    outsamp=16000 if forSTT else 48000
    subprocess.run([
        "ffmpeg",
        "-loglevel", "quiet",         # or "-v", "error"
        # ---------- 输入端 ----------
        "-f", "s16le",                
        "-ar", "44100",              
        "-ac", "2",                  
        "-i", "audio.pcm",
        # ---------- 转换处理 ----------
        "-ar", str(outsamp),         
        "-ac", "1",                  
        # "-filter:a", "volume=0.01",  
        # ---------- 输出端 ----------
        "-f", "s16le",               
        "-y",                        
        "recorded.pcm"
    ])
    print("转码完成。")
def main(forSTT=False):
    singleRecord()
    convertAudio(forSTT)
    if not forSTT:
        playaudio.main("recorded.pcm")

import numpy as np

def calculate_db_from_pcm(file_path):
    # Read the PCM file
    with open(file_path, 'rb') as f:
        pcm_data = f.read()

    # Convert the byte data to numpy array of int16
    audio_samples = np.frombuffer(pcm_data, dtype=np.int16)

    # Calculate RMS value
    rms = np.sqrt(np.mean(audio_samples**2))

    # Calculate dB level
    db_level = 20 * np.log10(rms) if rms > 0 else -np.inf

    return db_level


if __name__ == "__main__":
    db_level = calculate_db_from_pcm(f"{AUDIO_ROOT}/USBAudio/audio.pcm")
    print(f"Audio dB level: {db_level:.2f} dB")
    main(False)
